using Godot;
using Godot.Collections;
using System;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;

public partial class MultiplayerScene : Control
{
	public string ip;
	public int port = 8888;
	public override void _Ready()
	{
		Load();
		GetNode<Timer>("Timer_Tick").Timeout += Tick;
	}

	public override void _Process(double delta)
	{
		if (machingTime >= 0) machingTime += delta * 1f;
	}
	public void Tick()
	{

		foreach (var key in players.Keys)
		{
			Player player = players[key];
			RpcId(player.id, "SetPlayer", player.ToDictionary());
		}
		//同步对局
		for (int i = 0; i < inGames.Count; i++)
		{
			InGame inGame = inGames[i];
			bool remove = false;
			if (!players.ContainsKey(inGame.playerA.id))
			{
				RpcId(inGame.playerB.id, "TargetDisconnected");
				inGame.playerB.ingame = false;
				remove = true;
			}
			if (!players.ContainsKey(inGame.playerB.id))
			{
				RpcId(inGame.playerA.id, "TargetDisconnected");
				inGame.playerA.ingame = false;
				remove = true;
			}
			if (remove) inGames.Remove(inGame);
			else
			{
				var r = inGame.ChekWin();
				if (r.Item1 || inGame.Chekdeuce())
				{
					inGame.roundChessman = 1;
					inGame.guid = new int[3, 3];
					if (r.Item1) inGame.GetPlayer(r.Item2).point += 1;
					var chessman = inGame.playerA.chessman;
					inGame.playerA.chessman = inGame.playerB.chessman;
					inGame.playerB.chessman = chessman;
				}

				Dictionary dict = inGame.ToDictionary();
				RpcId(inGame.playerA.id, "SetInGame", dict);
				RpcId(inGame.playerB.id, "SetInGame", dict);
			}
		}
		//游戏匹配

		Player last = null;
		foreach (var key in players.Keys)
		{
			Player player = players[key];
			if (player.matching && !player.ingame)
			{
				if (last == null) last = player;
				else
				{
					if (new Random().Next(1) > 0.5f)
					{
						last.SetFirstChessman(1);
						player.SetFirstChessman(2);
					}
					else
					{
						last.SetFirstChessman(2);
						player.SetFirstChessman(1);
					}
					last.matching = false;
					last.point = 0;
					last.roomid = roomcount;
					last.ingame = true;
					player.matching = false;
					player.roomid = roomcount;
					player.ingame = true;
					player.point = 0;

					var ingame = new InGame()
					{
						roomid = roomcount,
						roundChessman = 1,
						playerA = last,
						playerB = player
					};
					roomcount++;
					inGames.Add(ingame);
					GD.Print($"匹配成功:{last.name},{player.name}");
					last = null;
				}
			}
		}
	}
	public void StartServer()
	{
		var peer = new ENetMultiplayerPeer();
		peer.CreateServer(port, 1000);
		Multiplayer.MultiplayerPeer = peer;
		Multiplayer.MultiplayerPeer.PeerConnected +=
		(long id) =>
		{
			var player = new Player()
			{
				id = id
			};
			players.Add(id, player);
			Rpc("SetOnlineCount", players.Count);
		};
		Multiplayer.MultiplayerPeer.PeerDisconnected +=
		(long id) =>
		{
			if (players.ContainsKey(id))
				players.Remove(id);
			Rpc("SetOnlineCount", players.Count);
		};

		GD.Print("[启动服务器]");
	}
	public void ConnectServer()
	{
		var peer = new ENetMultiplayerPeer();
		peer.CreateClient(ip, port);
		Multiplayer.MultiplayerPeer = peer;
		Multiplayer.ConnectedToServer += () => GD.Print("[连接服务器]");
	}
	public void Load()
	{
		if (!FileAccess.FileExists("config.json"))
		{
			Save();
		}
		var file = FileAccess.Open("config.json", FileAccess.ModeFlags.Read);
		Dictionary dict = (Dictionary)Json.ParseString(file.GetAsText());
		ip = (string)dict["ip"];
		port = (int)dict["port"];
		string type = "";
		type = (string)dict["type"];
		if (type == "server")
			StartServer();
		else if (type == "cilent")
			ConnectServer();
		file.Close();
	}
	public void Save()
	{
		var file = FileAccess.Open("config.json", FileAccess.ModeFlags.Write);
		Dictionary dict = new Dictionary(){
			{"ip","127.0.0.1"},
			{"port",8888},
			{"type","cilent"}
		};
		file.StoreString(Json.Stringify(dict));
		file.Close();
	}
}
